package settings

import (
	"encoding/json"
	"fmt"
	"strconv"
	"time"
)

type Setting struct {
	ID        uint      `json:"id" gorm:"primaryKey"`
	TenantID  uint      `json:"tenant_id" gorm:"index"`
	Key       string    `json:"key" gorm:"size:50"`
	Value     string    `json:"value" gorm:"type:text"`      // Text 类型
	ValueType int       `json:"value_type" gorm:"default:1"` // 1:字符串 2:数字 3:布尔值 4:JSON
	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`
}

func (Setting) TableName() string {
	return "system_setting"
}

func (s *Setting) GetStringValue() (string, error) {
	if s.ValueType != 1 {
		return "", fmt.Errorf("value type is not string")
	}
	return s.Value, nil
}

func (s *Setting) GetNumberValue() (int, error) {
	if s.ValueType != 2 {
		return 0, fmt.Errorf("value type is not number")
	}
	return strconv.Atoi(s.Value)
}

func (s *Setting) GetBoolValue() (bool, error) {
	if s.ValueType != 3 {
		return false, fmt.Errorf("value type is not boolean")
	}
	return strconv.ParseBool(s.Value)
}

// GetJSONValueAs 将设置值解析为指定类型
func (s *Setting) GetJSONValueAs(result any) error {
	if s.ValueType != 4 {
		return fmt.Errorf("value type is not json")
	}

	if err := json.Unmarshal([]byte(s.Value), result); err != nil {
		return err
	}

	return nil
}

// GetJSONValueAs 将 JSON 值转换为指定类型
func GetJSONValueAs[T any](s string, result *T) error {
	if err := json.Unmarshal([]byte(s), result); err != nil {
		return err
	}
	return nil
}
